package cn.smileyan.demos.operators;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class ReduceDemo {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<Tuple2<Integer, String>> groupInput = env.fromElements(
                Tuple2.of(1, "apple"),
                Tuple2.of(2, "banana"),
                Tuple2.of(1, "cherry"),
                Tuple2.of(2, "elderberry"),
                Tuple2.of(1, "firefly"),
                Tuple2.of(2, "giraffe"),
                Tuple2.of(2, "hippopotamus")
        );

        SingleOutputStreamOperator<String> output = groupInput.keyBy(v -> v.f0)
                .reduce(new ReduceFunction<Tuple2<Integer, String>>() {
                    @Override
                    public Tuple2<Integer, String> reduce(Tuple2<Integer, String> result, Tuple2<Integer, String> t1) throws Exception {
                        return Tuple2.of(result.f0, result.f1 + ";" + t1.f1);
                    }
                })
                .map(v -> v.f1);

        output.print();

        env.execute();
    }
}
